﻿/* 
 * Since 2008 - 2012
 */

package com.hh.bss.project.dao.impl;

import static com.hh.bss.util.ObjectUtils.isNotEmpty;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Repository;

import com.hh.bss.base.BaseHibernateDao;
import com.hh.bss.common.MapObjectRowMapper;
import com.hh.bss.common.page.Page;
import com.hh.bss.project.dao.ContractJobOfferPartnerDao;
import com.hh.bss.project.entity.ContractJobOfferPartner;
import com.hh.bss.project.vo.query.ContractJobOfferPartnerQuery;
import com.hh.bss.util.DateHelper;
import com.hh.bss.util.StringHelper;

@Repository
public class ContractJobOfferPartnerDaoImpl extends BaseHibernateDao<ContractJobOfferPartner, java.lang.Integer> implements ContractJobOfferPartnerDao<ContractJobOfferPartner, java.lang.Integer> {

	public Class getEntityClass() {
		return ContractJobOfferPartner.class;
	}

	public Page findPage(ContractJobOfferPartnerQuery query) {
		// XsqlBuilder syntax,please see
		// http://code.google.com/p/rapid-xsqlbuilder
		// [column]为字符串拼接, {column}为使用占位符.
		// [column]为使用字符串拼接,如username='[username]',偷懒时可以使用字符串拼接
		// [column] 为PageRequest的属性

		Class[] os = { ContractJobOfferPartnerQuery.class };
		Class property = org.springframework.beans.BeanUtils.findPropertyType(query.getField_type(), os);
		if (property != null) {
			if ("java.lang.String".equals(property.getName())) {

				com.hh.bss.util.BeanUtils.setProperty(query, query.getField_type(), query.getQuery());

			} else if ("java.lang.Integer".equals(property.getName())) {

				com.hh.bss.util.BeanUtils.setProperty(query, query.getField_type(), StringHelper.parseInteger(query.getQuery(), 0));

			} else if ("java.lang.Double".equals(property.getName())) {
				com.hh.bss.util.BeanUtils.setProperty(query, query.getField_type(), StringHelper.parseDouble(query.getQuery(), 0));
			} else if ("java.util.Date".equals(property.getName())) {
				com.hh.bss.util.BeanUtils.setProperty(query, query.getField_type(), DateHelper.toDate(query.getQuery(), DateHelper.DEFAULT_DATE_FORMAT));
			}
		}
		// 生成sql2的原因是为了不喜欢使用xsqlbuilder的同学，请修改生成器模板，删除本段的生成
		StringBuilder sql2 = new StringBuilder("select t from ContractJobOfferPartner t where 1=1 ");
		if (isNotEmpty(query.getId())) {
			sql2.append(" and  t.id = :id ");
		}
		if (isNotEmpty(query.getOfferId())) {
			sql2.append(" and  t.offerId = :offerId ");
		}
		if (isNotEmpty(query.getRole())) {
			sql2.append(" and  t.role like :role ");
			query.setRole("%" + query.getRole() + "%");

		}
		if (isNotEmpty(query.getAccount())) {
			sql2.append(" and  t.account like :account ");
			query.setAccount("%" + query.getAccount() + "%");

		}
		if (isNotEmpty(query.getPercent())) {
			sql2.append(" and  t.percent = :percent ");
		}
		if (isNotEmpty(query.getAmount())) {
			sql2.append(" and  t.amount = :amount ");
		}
		if (isNotEmpty(query.getCreator())) {
			sql2.append(" and  t.creator like :creator ");
			query.setCreator("%" + query.getCreator() + "%");

		}
		if (isNotEmpty(query.getCreateDtBegin())) {
			sql2.append(" and  t.createDt >= :createDtBegin ");
		}
		if (isNotEmpty(query.getCreateDtEnd())) {
			sql2.append(" and  t.createDt <= :createDtEnd ");
		}
		if (isNotEmpty(query.getModifier())) {
			sql2.append(" and  t.modifier like :modifier ");
			query.setModifier("%" + query.getModifier() + "%");

		}
		if (isNotEmpty(query.getModifiedDtBegin())) {
			sql2.append(" and  t.modifiedDt >= :modifiedDtBegin ");
		}
		if (isNotEmpty(query.getModifiedDtEnd())) {
			sql2.append(" and  t.modifiedDt <= :modifiedDtEnd ");
		}
		if (isNotEmpty(query.getSortColumns())) {
			sql2.append(" order by :sortColumns ");
		}

		return pageQuery(sql2.toString(), query);
	}

	@Override
	/**
	 * 检查是否有重复记录
	 */
	public boolean checkSameRoleAndAccount(ContractJobOfferPartner offerPartner) {
		StringBuffer sql = new StringBuffer(" select * from contract_job_offer_partner a where  a.role = ? and a.account = ? ");
		List values = new ArrayList();
		values.add(offerPartner.getRole());
		values.add(offerPartner.getAccount());
		List list = this.getJdbcDao().findByQuery(sql.toString(), values.toArray(), new MapObjectRowMapper());
		if (list != null && list.size() > 0) {
			return true;
		}
		return false;
	}

	@Override
	public void addPartnerWithJob(Integer jobId) {
		if (jobId != null && jobId > 0) {
			List values = new ArrayList();
			StringBuffer sql = new StringBuffer();
			sql.append(" insert into contract_job_offer_partner(offer_id,role,account,percent,amount,creator,create_dt,modifier,modified_dt) ");
			sql.append(" select d.id,b.role,b.account,b.percent,b.amount,b.creator,b.create_dt,b.modifier,b.modified_dt ");
			sql.append(" from contract_job a,contract_job_partner b  ");
			sql.append(" ,contract_job_cv_recom c,contract_job_cv_offer d ");
			sql.append(" where a.id=b.job_id and c.job_id=a.id and c.id=d.recom_id ");
			sql.append(" and not exists(select 1 from contract_job_offer_partner cc where cc.offer_id=d.id and b.account=cc.account and cc.role=b.role ) ");
			sql.append(" and a.id= " + jobId + " ");
			// 没有账单才进行同步
			sql.append(" and not exists (select 1 from account_pn p1 where  p1.offer_id = d.id  ) ");
			// values.add(jobId);
			this.getJdbcDao().getJdbcTemplate().execute(sql.toString());
		}

	}

	@Override
	public void updatePartnerWithJob(Integer jobId) {
		if (jobId != null && jobId > 0) {
			StringBuffer sql = new StringBuffer();
			/*
			 * sql.append(" delete from contract_job_offer_partner  ");
			 * sql.append(
			 * " where not exists(select 1 from contract_job a,contract_job_partner b ,contract_job_cv_recom c,contract_job_cv_offer d "
			 * ); sql.append(
			 * " where a.id=b.job_id and c.job_id=a.id and c.id=d.recom_id and contract_job_offer_partner.offer_id=d.id and contract_job_offer_partner.account=b.account "
			 * ); sql.append(
			 * " where a.id=b.job_id and c.job_id=a.id and c.id=d.recom_id and aa.offer_id=d.id and aa.account=cc.account "
			 * );
			 * sql.append("  and contract_job_offer_partner.role=b.role )  ");
			 * sql.append(
			 * " and exists(select 1 from contract_job a,contract_job_partner b ,contract_job_cv_recom c,contract_job_cv_offer d "
			 * ); sql.append(
			 * " where a.id=b.job_id and c.job_id=a.id and c.id=d.recom_id and contract_job_offer_partner.offer_id=d.id and a.id="
			 * +jobId+" )");
			 */
			sql.append("delete t1 from contract_job_offer_partner t1 where not exists ( select 1 from contract_job a, contract_job_partner b, contract_job_cv_recom c, contract_job_cv_offer d WHERE a.id = b.job_id AND c.job_id = a.id AND c.id = d.recom_id AND t1.offer_id = d.id AND t1.account = b.account AND t1.role = b.role ) AND EXISTS ( SELECT 1 FROM contract_job a, contract_job_partner b, contract_job_cv_recom c, contract_job_cv_offer d WHERE a.id = b.job_id AND c.job_id = a.id AND c.id = d.recom_id AND t1.offer_id = d.id AND a.id = " + jobId + " )");
			sql.append(" and not exists (select 1 from account_pn p1 where  p1.offer_id = t1.offer_id  ) ");
			this.getJdbcDao().getJdbcTemplate().execute(sql.toString());
		}

	}

	@Override
	public boolean validateOfferPartner(ContractJobOfferPartner offerPartner) {
		log.info("Dao 执行了..");
		if (offerPartner != null) {
			if (StringUtils.isNotEmpty(offerPartner.getRole())) {
				// 如果是 职位负责人 和 合作顾问 验证业绩
				if ("MC".equals(offerPartner.getRole()) || "PC".equals(offerPartner.getRole())) {
					StringBuffer sql = new StringBuffer();
					List values = new ArrayList();
					sql.append("select ifnull(sum(a.percent),0) percentSum from  contract_job_offer_partner a where 1=1 and (a.role='MC' or a.role='PC') and a.offer_id = ? and a.id <> ? ");
					values.add(offerPartner.getOfferId());
					values.add(offerPartner.getId());
					try {
						Double percent = this.getJdbcDao().getJdbcTemplate().queryForObject(sql.toString(), values.toArray(), Double.class);
						logger.info("参数是:" + offerPartner.getPercent());
						logger.info("总数是:" + (percent + offerPartner.getPercent()));
						if ((offerPartner.getPercent() + percent) <= 100.00d) {
							return true;
						}
					} catch (Exception ex) {
						ex.printStackTrace();
					}
				}
			}
		}
		return false;
	}

	@Override
	public boolean isJobOfferPartner(ContractJobOfferPartner offerPartner) {
		if ("admin".equals(offerPartner.getModifier())) {
			return true;
		}
		StringBuffer sql = new StringBuffer();
		List values = new ArrayList();
		sql.append("select count(a.account) count from contract_job_offer_partner a where  a.offer_id = ?  and a.account = ?  ");
		values.add(offerPartner.getOfferId());
		values.add(offerPartner.getModifier());
		Integer percent = this.getJdbcDao().getJdbcTemplate().queryForObject(sql.toString(), values.toArray(), Integer.class);
		return percent > 0;
	}

}
